package com.woniuxy.util;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author：xurice
 * @date：Created in 2024/4/20 15:18
 * @description：初始化数据库工具类
 * @modified By：
 * @version: $
 */
@Component
public class InitDBUtil {

    private static final String jdbcUrlTemplate = "jdbc:mysql://#{mysqlUrl}/hospital?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowMultiQueries=true";
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String dropSchemaSqlTemplate = "DROP DATABASE IF EXISTS #{schema}";
    private static final String createSchemaSqlTemplate = " CREATE DATABASE `#{schema}`";
    private static final String useSchemaSqlTemplate = "use `#{schema}`;";

    //创建数据库
    public static boolean initDB(String mysqlUrl, String schema, String username, String password) {
        Connection connection = null;
        try {
            Class.forName(driver);

            String replace = jdbcUrlTemplate.replace("#{mysqlUrl}", mysqlUrl);
            System.out.println(replace);
            connection = DriverManager.getConnection(replace, username, password);

            Statement statement = connection.createStatement();
            statement.execute(dropSchemaSqlTemplate.replace("#{schema}", schema));
            statement.execute(createSchemaSqlTemplate.replace("#{schema}", schema));
            statement.execute(useSchemaSqlTemplate.replace("#{schema}", schema));

            //mybatis提供的脚本执行
            ScriptRunner scriptRunner = new ScriptRunner(connection);
            scriptRunner.setStopOnError(true);

            ClassPathResource classPathResource = new ClassPathResource("hospital.sql");
            InputStream inputStream = classPathResource.getStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            scriptRunner.runScript(isr);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (null != connection) {
                try {
                    connection.commit();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //尝试连接数据库
    public static boolean tryConnectDB(String mysqlUrl, String schema, String username, String password) {
        Connection connection=null;

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(jdbcUrlTemplate.replace("#{mysqlUrl}", mysqlUrl), username, password);
            return true;
        } catch (Exception e) {
            return false;
        }  finally {
            try {
                connection.commit();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static DruidDataSource getInitDb(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        return dataSource;
    }

    @Bean
    public DynamicRoutingDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setPassword("10b950d19a58db6a");
        dataSource.setUsername("root");
        dataSource.setUrl("jdbc:mysql://1.94.116.28:3306/hospital?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true");
        DynamicRoutingDataSource source = new DynamicRoutingDataSource();
        source.addDataSource("master",dataSource);
        return source;
    }

}
